import { computed } from 'vue'

// 权限分组颜色映射
const permissionGroupColors = {
    'dashboard': 'primary',
    'user': 'success',
    'role': 'warning',
    'personal': 'info',
    'system': 'danger',
    'default': ''
}

export function usePermissionDisplay() {
    // 根据权限前缀获取对应的颜色类型
    const getPermissionColor = (permission) => {
        if (!permission || typeof permission !== 'string') return permissionGroupColors.default
        const prefix = permission.split(':')[0]
        return permissionGroupColors[prefix] || permissionGroupColors.default
    }

    // 按权限前缀分组显示
    const groupPermissions = (permissions) => {
        // 确保 permissions 是一个有效数组
        if (!Array.isArray(permissions)) return {}
        
        const groups = {}
        permissions.forEach(permission => {
            // 确保 permission 是字符串
            if (typeof permission !== 'string') return
            const prefix = permission.split(':')[0]
            if (!groups[prefix]) {
                groups[prefix] = []
            }
            groups[prefix].push(permission)
        })
        return groups
    }

    // 检查权限数量是否少于5个
    const isFewPermissions = (permissions) => {
        return permissions && Array.isArray(permissions) && permissions.length <= 4
    }

    // 处理权限显示，确保返回的是数组
    const processPermissionsDisplay = (permissions) => {
        if (!permissions) return []
        return Array.isArray(permissions) ? permissions : [permissions]
    }

    // 获取权限显示配置
    const getPermissionDisplayConfig = (permissions) => {
        return {
            shouldUsePopover: !isFewPermissions(permissions),
            groupedPermissions: groupPermissions(permissions),
            totalCount: Array.isArray(permissions) ? permissions.length : 0
        }
    }

    return {
        getPermissionColor,
        groupPermissions,
        isFewPermissions,
        processPermissionsDisplay,
        getPermissionDisplayConfig
    }
}